# @File    : yamlUtil.py
# @Project : Airtest_JBL
# YAML文件读取类
import os
from string import Template
import yaml


class YamlUtil:

    def __init__(self, filename):
        self.filename = filename
        self.path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + "\\" + "data" + "\\" + f'{filename}'

    # 读取yaml文件内容
    def read_yaml(self):
        with open(self.path, mode="r", encoding="utf-8") as f:
            value = yaml.load(stream=f, Loader=yaml.FullLoader)
            return value

    # 写入
    def write_yaml(self, data):
        with open(self.path, mode="a", encoding="utf-8") as f:
            yaml.dump(data, stream=f, allow_unicode=True, sort_keys=False)

    def overwrite(self, data):
        with open(self.path, mode="w", encoding="utf-8") as f:
            f.write(data)

    # 替代
    def yaml_template(self, data):
        with open(self.path, encoding="utf-8") as f:
            read_template = Template(f.read()).safe_substitute(data)
            return yaml.safe_load(read_template)

    # 清空
    def clean_yaml(self):
        with open(self.path, mode="w", encoding="utf-8") as f:
            f.truncate()

